extends CanvasLayer

var in_dialogue := false
var lines: Array = []          # 对话内容（数组）
var current_index := 0         # 当前是第几句
var typing := false            # 是否正在逐字打印
var char_speed := 0.02         # 每个字符显示间隔（可改）
@onready var label: Label = $Panel/Label

func start_dialogue(new_lines: Array):
	if in_dialogue:
		return
	in_dialogue = true
	visible = true
	lines = new_lines
	current_index = 0
	_show_line()

func _show_line():
	label.text = ""
	typing = true
	var text = lines[current_index]
	for c in text:
		label.text += c
		await get_tree().create_timer(char_speed).timeout
		if not typing:
			label.text = text
			break
	typing = false

func _process(delta):
	if not visible:
		return
	if Input.is_action_just_pressed("interact"):
		if typing:
			typing = false
		else:
			_next_line()

func _next_line():
	current_index += 1
	if current_index >= lines.size():
		close()
	else:
		_show_line()

func close():
	visible = false
	in_dialogue = false
